package controller

import (
	"fmt"
	"illuminant/config"
	"illuminant/logger"
	"illuminant/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

func PGDumpSchema(c *gin.Context) {
	lg := logger.GetLogger()
	conf := config.Get()

	data, err := util.PostJson(conf.Graphql.PGDumpURL, map[string]interface{}{
		"clean_output": false,
		"opts":         []string{"-O", "-x", "--schema-only"},
	})
	if err != nil {
		lg.Err(err).Msg("pg dump error")
		util.Fail(c, util.FAIL, "dump database failed", nil)
		return
	}

	writeFileResponse(c, "database.sql", string(data))
}

func HasuraMetaData(c *gin.Context) {
	lg := logger.GetLogger()
	conf := config.Get()

	data, err := util.PostJson(conf.Graphql.MetaDataURL, map[string]interface{}{
		"type": "export_metadata",
		"args": nil,
	})
	if err != nil {
		lg.Err(err).Msg("export metadata error")
		util.Fail(c, util.FAIL, "export metadata failed", nil)
		return
	}

	writeFileResponse(c, "metadata.json", string(data))
}

func writeFileResponse(c *gin.Context, fn, content string) {
	c.Writer.WriteHeader(http.StatusOK)
	c.Header("Content-Disposition", "attachment; filename="+fn)
	c.Header("Content-Type", "application/text/plain")
	c.Header("Accept-Length", fmt.Sprintf("%d", len(content)))
	c.Writer.Write([]byte(content))
}
